package com.moyun.zbmy.zizhou.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FCityItem;
import com.moyun.zbmy.zizhou.beans.FCityNews;
import com.moyun.zbmy.zizhou.beans.FGovItem;
import com.moyun.zbmy.zizhou.beans.GovItemBean;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.ServiceItem;
import com.moyun.zbmy.zizhou.ui.activities.MoreServiceActivity;
import com.moyun.zbmy.zizhou.ui.adapter.CityStaChannelAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.CultureTravelAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.ServiceAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.GovServiceHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.NormalServiceHolder;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.base.BaseFragment;
import com.moyun.zbmy.zizhou.beans.CityServiceBean;
import com.moyun.zbmy.zizhou.beans.FRebellion;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.JSBeans;
import com.moyun.zbmy.zizhou.beans.MallJsonVo;
import com.moyun.zbmy.zizhou.beans.ServiceBean;
import com.moyun.zbmy.zizhou.beans.ServiceCityListVo;
import com.moyun.zbmy.zizhou.beans.ServiceConfigBean;
import com.moyun.zbmy.zizhou.beans.ServiceDataBean;
import com.moyun.zbmy.zizhou.beans.ServiceVo;
import com.moyun.zbmy.zizhou.beans.UserInfoBean;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.activities.H5NormalActivity;
import com.moyun.zbmy.zizhou.ui.activities.LoginActivity;
import com.moyun.zbmy.zizhou.ui.activities.NewH5Activity;
import com.moyun.zbmy.zizhou.ui.adapter.ServicePagerAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.ServiceRecentlyUsedServiceAdapter;
import com.moyun.zbmy.zizhou.utils.GaoDeLocationUtil;
import com.moyun.zbmy.zizhou.utils.UserManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

public class ServiceFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, GovServiceHolder.OnGovServiceClick
        , CanRefreshLayout.OnLoadMoreListener , NormalServiceHolder.OnServiceItemClick, OnItemInternalClick {
    private static final int TO_EXCHANGE_CITY = 1;
    private static final int CODE_REQUEST_LOGIN = 2;
    //    private String serviceUrl = "";
//    public static final String configUrl = "/sctv/appConfig.json";
//    private String cityUrl;
    private static final String RECENTLY_USED_SERVICE = "recently_used_service";

    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;


    private FCityItem cityItem=new FCityItem();
    private ServiceAdapter adapter;
    private LinearLayoutManager channelManager;
    private List<IListShowData> newsList = new ArrayList<>();
    private String serviceUrlTemp, bannerUrlTemp;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_service, container, false);
        ButterKnife.bind(this, view);
        Cache.getInstance().setCurrentChannelId("");
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
//        channelUrl="sctv/jingxuan2/index/jingxuan2.json";
        channelManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(channelManager);
        refreshLayout.autoRefresh();
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            Cache.getInstance().setCurrentChannelId("");
        } else {

        }

    }

    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case ServiceAdapter.VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_EXPRESS:
//                                    expressUrlTemp = fc.getChannelUrl();
//                                    break;
                                case ServiceAdapter.VIEWTYPE_SERVICE:
                                    serviceUrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_POPULAR:
//                                    popularUrlTemp = fc.getChannelUrl();
//                                    break;
                            }
                        }
                    }

                    if (!getBannerArray(bannerUrlTemp, ServiceAdapter.VIEWTYPE_BANNER)) {
//                        dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_BANNER);
                    }

                }else{
                    refreshLayout.refreshComplete();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }


        });
    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
        serviceUrlTemp = null;
    }
    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @param mode
     * @return
     */
    private boolean getBannerArray(String url, final int mode) {

//        if (!groupOrderHelper.addOne(mode)) {
//            return false;
//        }
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(ServiceAdapter.VIEWTYPE_BANNER);
                    newsList.add(hb);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                onNetFinish();
            }

            @Override
            public void onEnd() {
                super.onEnd();
                getCityStateList();
            }
        });
        return true;
    }

    /**
     * 获取市州机构列表
     */
    private void getCityStateList() {
        NetUtils.getNetAdapter().getStateList(getOwnerName(), serviceUrlTemp, new AbsNetCallBack<FCityItem>(FCityItem.class) {
            @Override
            public void onSuc(FCityItem fCityItem) {
                if (fCityItem != null) {
                    cityItem.setInstitutionList(fCityItem.getInstitutionList());
                    setStateData(fCityItem);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                onNetFinish();
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }
    private void setStateData(FCityItem fCityItem) {
        if(ListUtils.isListValued(fCityItem.getInstitutionList())) {
            if (fCityItem.getInstitutionList() != null && fCityItem.getInstitutionList().size() <= 2) {
                fCityItem.setViewType(0);
                newsList.add(fCityItem);
                onNetFinish();
            } else {
                FCityItem item = new FCityItem();
                List<GovItemBean> beans = new ArrayList<>();
                beans.add(fCityItem.getInstitutionList().get(0));
                beans.add(fCityItem.getInstitutionList().get(1));
                item.setViewType(0);
                item.setInstitutionList(beans);
                newsList.add(item);
                for(int i=0;i<2;i++){
                    fCityItem.getInstitutionList().remove(0);
                }
                Collections.sort(fCityItem.getInstitutionList());
                getServiceDynamicList(fCityItem);
//                for (GovItemBean bean : fCityItem.getInstitutionList()) {
//                    bean.setViewType(2);
////                    newsList.add(bean);
//                    getServiceDynamicList(bean);
//                }
            }
        }else {
            onNetFinish();
        }

    }

    private  void getServiceDynamicList(FCityItem cityItem){
        if(ListUtils.isListValued(cityItem.getInstitutionList())) {
            for (int i = 0; i < cityItem.getInstitutionList().size(); i++) {
                GovItemBean bean= cityItem.getInstitutionList().get(i);
                getServiceDynamicList(bean);
            }

        }
    }

    /**
     * 获取机构新闻列表
     */
    private synchronized void getServiceDynamicList(final GovItemBean bean) {
        if (TextUtils.isEmpty(bean.getInstitutionUrl())|| !bean.getInstitutionUrl().endsWith(".json")) {
            toast("数据错误");
            return ;
        }


        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), bean.getInstitutionUrl(),0,new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                     bean.setViewType(2);
                     bean.setInfoList(newsItems);
                     newsList.add(bean);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });

    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if(ListUtils.isListValued(newsList)){
            List<GovItemBean> beans=new ArrayList<>();
            Iterator<IListShowData> iterator=newsList.iterator();
            while(iterator.hasNext()){
                IListShowData showData=iterator.next();
                if(showData instanceof GovItemBean){
                    beans.add((GovItemBean) showData);
                    iterator.remove();
                }
            }
            if(ListUtils.isListValued(beans)){
                Collections.sort(beans);
                newsList.addAll(beans);
            }
            if(adapter==null) {
                adapter = new ServiceAdapter(getContext(), newsList,this);
                adapter.setBannerActiveClick(this);
                adapter.setServiceClick(this);
                recyclerView.setAdapter(adapter);
            }else {
                adapter.setData(newsList);
//                adapter.notifyDataSetChanged();
            }
        }
    }
    private void toH5(NewsItem item){
        if(item.getNewsUrl().equalsIgnoreCase("http://file.scwy.tv/logo/page.html")) {
            if (UserManager.isLoginS()) {
                Intent intent = new Intent(getContext(), NewH5Activity.class);
                intent.putExtra(EX_TITLE, item.getDataTitle());
                intent.putExtra(EX_HTML, item.getNewsUrl());
                startActivity(intent);
            } else {
                toLogin();
            }
        }else{
            Intent intent = new Intent(getContext(), H5NormalActivity.class);
            intent.putExtra(EX_TITLE, item.getDataTitle());
            intent.putExtra(EX_HTML, item.getNewsUrl());
            startActivity(intent);
        }
    }


    @Override
    public void onDestroyView() {
        GaoDeLocationUtil.getInstance().stopLocate();
        super.onDestroyView();
    }


    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }






    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {

            }
        }
    }


    @Override
    public void onLoadMore() {

    }

    @Override
    public void onRefresh() {
        if(newsList!=null){
            newsList.clear();
        }
        getChannelList();
    }

    @Override
    public void OnServiceItemClick(NewsItem item) {
        toH5(item);
    }

    @Override
    public void OnItemClick(GovItemBean govItemBean) {
        Intent intent=new Intent(getActivity(), MoreServiceActivity.class);
        Bundle bundle=new Bundle();
//        bundle.putSerializable(BaseActivity.EX_DATA,cityItem);
        bundle.putString(BaseActivity.EX_URL,serviceUrlTemp);
        bundle.putSerializable(BaseActivity.EX_NEWS_ITEM,govItemBean);
        intent.putExtras(bundle);
        getActivity().startActivity(intent);
    }

    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        if(view.getId()==R.id.tv_more){

        }
    }

    @Override
    public void OnGovServiceClick(GovItemBean item) {
        Intent intent=new Intent(getActivity(), MoreServiceActivity.class);
        Bundle bundle=new Bundle();
//        bundle.putSerializable(BaseActivity.EX_DATA,cityItem);
        bundle.putString(BaseActivity.EX_URL,serviceUrlTemp);
        bundle.putSerializable(BaseActivity.EX_NEWS_ITEM,item);
        intent.putExtras(bundle);
        getActivity().startActivity(intent);
    }
}